<?php

class ChecklistPerizinanController extends Controller
{
    public $layout='//layouts/column2';

    protected function getIndexList($model) {
        $indexList = array(
            array(
		'name' => 'izin_id',
		'visible' => false,
		'value' => '($data->Izin) ? $data->Izin->id : "-"',
	),array(
		'name' => 'perizinan_id',
		'visible' => false,
		'value' => '($data->Perizinan) ? $data->Perizinan->nama : "-"',
	),array(
		'name' => 'status_kelengkapan',
		'visible' => false,
		'value' => '($data->status_kelengkapan) ? $data->status_kelengkapan : "-"',
	),array(
		'name' => 'upload_dokumen',
		'visible' => false,
		'value' => '($data->upload_dokumen) ? $data->upload_dokumen : "-"',
	),            array(
                'htmlOptions' => array('nowrap'=>'nowrap','class'=>'button-column'),
                'class'=>'booster.widgets.TbButtonColumn'
            ),
        );
        return $indexList;
    }

    protected function getViewList($model) {
        $viewList = array(
            array(
	'name' => 'perizinan_id',
	'value' => ($model->perizinan) ? $model->perizinan->nama : "-",
),array(
	'name' => 'status_kelengkapan',
	'value' => ($model->status_kelengkapan) ? $model->status_kelengkapan : "-",
),array(
	'name' => 'nomor_sk',
	'value' => ($model->izin->nomor_sk) ? $model->izin->nomor_sk : "-",
),array(
	'name' => 'tentang',
	'value' => ($model->izin->tentang) ? $model->izin->tentang : "-",
),array(
	'name' => 'tanggal_terbit',
	'value' => ($model->izin->tanggal_terbit) ? $model->izin->tanggal_terbit : "-",
),array(
	'name' => 'tanggal_berakhir',
	'value' => ($model->izin->tanggal_berakhir) ? $model->izin->tanggal_berakhir : "-",
),array(
	'name' => 'penanggung_jawab',
	'value' => ($model->izin->penanggung_jawab) ? $model->izin->penanggung_jawab : "-",
),array(
	'name' => 'kode_izin_usaha',
	'value' => ($model->izin->kode_izin_usaha) ? $model->izin->kode_izin_usaha : "-",
),array(
	'name' => 'kapasitas_pengolahan',
	'value' => ($model->izin->kapasitas_pengolahan) ? $model->izin->kapasitas_pengolahan : "-",
),array(
	'name' => 'lokasi',
	'value' => ($model->izin->lokasi) ? $model->izin->lokasi.', '.$model->izin->provinsi->nama : $model->izin->kabupaten->nama.', '.$model->izin->provinsi->nama,
),
            array(
	'name' => 'status_izin',
	'value' => ($model->izin->status_izin) ? $model->izin->status_izin : "-",
),array(
	'name' => 'upload_dokumen',
        'type'=>'raw',
	'value' => ($model->upload_dokumen) ? CHtml::link($model->upload_dokumen, array('checklistPerizinan/download/'.$model->id),array('target'=>'_blank')) : "-",
));
        return $viewList;
    }
    
    public function actionDownload($id) {
        $model = $this->loadModel($id);
        $path = YiiBase::getPathOfAlias('webroot').$model->path_dokumen;
        clearstatcache();
        ob_end_clean();
        if (!empty($model->upload_dokumen) && file_exists($path.$model->upload_dokumen)) {
            $file = $path.$model->upload_dokumen;
            header('Pragma: public');
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
            header('Cache-Control: no-store, no-cache, must-revalidate');
            header('Cache-Control: pre-check=0, post-check=0, max-age=0');
            header ("Pragma: no-cache");
            header("Expires: 0");
            header('Content-Transfer-Encoding: none');
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Type: application/pdf');
            header('Content-Length: ' . filesize($file));
            header('Content-Disposition: attachment; filename="'.basename($model->upload_dokumen).'"');
            readfile($file);
            Yii::app()->end();
            return;
        } else {
            echo 'Berkas tidak tersedia';
        }
    }

    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    public function actionDetail($id)
    {
        $model=$this->loadModel($id);
        $data = Izin::model()->findByPk($model->izin_id);
        $this->render('detail', array(
            'model' => $model,
            'data'=>$data,
        ));
    }
    
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    public function actionCreate()
    {
        $model=new ChecklistPerizinan;
        $this->performAjaxValidation($model);
        if(isset($_POST['ChecklistPerizinan']))
        {
            $model->attributes=$_POST['ChecklistPerizinan'];
            if($model->save())
                $this->redirect(array($this->defaultAction));
        }
        $this->render('create',array(
            'model'=>$model,
        ));
    }

    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
        $izin = Izin::model()->findByPk($model->izin_id);
//        $this->performAjaxValidation($model);
        if(isset($_POST['ChecklistPerizinan'],$_POST['Izin']))
        {
            $model->attributes=$_POST['ChecklistPerizinan'];
            $izin->attributes=$_POST['Izin'];
            $izinID = $model->izin_id;
            $data = Izin::model()->with('perusahaan')->findByPk($izinID);
                $badanUsaha = $data->perusahaan->bentuk_badan_usaha;
                $nama = $data->perusahaan->nama_perusahaan;
                $perusahaanId = $data->perusahaan_id;
                $namaItem = $model->perizinan->nama;
                
                if($data->perusahaan->jenis_usaha == 'Pengolahan MB')
                    $dirName = '1 Pengolahan MB';
                if($data->perusahaan->jenis_usaha == 'Pengolahan GB')
                    $dirName = '2 Pengolahan GB';
                if($data->perusahaan->jenis_usaha == 'Pengolahan HO')
                    $dirName = '3 Pengolahan HO';
                $num = $model->perizinan->id;
                $fileName = $num.'-'.$badanUsaha.' '.$nama.'-'.$namaItem.'.pdf';
            $file = CUploadedFile::getInstance($model, 'upload_dokumen');
            if (is_object($file) && get_class($file) === 'CUploadedFile')
                $model->upload_dokumen = $file;
            if ($model->validate()) {
                $rootDir = '/uploaded_files/attachment/'.$dirName.'/'.$perusahaanId.' '.$badanUsaha.' '.$nama.'/3 Izin/';
                $path = YiiBase::getPathOfAlias('webroot').$rootDir;
                if (is_object($model->upload_dokumen)) {
                    $model->upload_dokumen->saveAs($path.$fileName);
                }
                
                $model->upload_dokumen = (!empty($model->upload_dokumen)) ? $fileName : '';
                $model->status_kelengkapan = (!empty($model->upload_dokumen)) ? 'Ada' : 'Tidak';
                $model->path_dokumen = (!empty($model->upload_dokumen)) ? $rootDir : '';
                
                if($model->save())
                {
                    $izin->perusahaan_id = $perusahaanId;
                    $izin->upload_dokumen = $fileName;
                    $izin->path_dokumen = $rootDir;
                    $izin->save();
                    $this->redirect(array('izin/'.$izinID));
                }
            }
        }
        $this->render('update',array(
            'model'=>$model,
            'izin'=>$izin,
        ));
    }

    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            $this->loadModel($id)->delete();
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function actionIndex()
    {
        $model=new ChecklistPerizinan('publik');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['ChecklistPerizinan']))
            $model->attributes=$_GET['ChecklistPerizinan'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
    * Manages all models.
    */
    public function actionAdmin()
    {
        $model=new ChecklistPerizinan('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['ChecklistPerizinan']))
            $model->attributes=$_GET['ChecklistPerizinan'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    public function loadModel($id)
    {
        $model=ChecklistPerizinan::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='checklist-perizinan-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
